import { addChatTitle, getTitleDetail, historyList } from "@/api/base";
import type { HistoryVO } from "@/api/base/types";
import useAuthStore from "@/store/auth";
import { useState, useEffect, useRef, useCallback } from "react";

// ==================== 类型定义 ====================
export interface Message {
  id: string;
  createTime: string;
  loading?: boolean;
  thinking?: boolean;
  content?: string;
  type?: string;
}

export interface UseChatOptions {
  apiEndpoint?: string;
  withContext?: boolean;
  onError?: (error: string) => void;
  onSuccess?: (message: Message) => void;
  onAddHistory?: (data: any) => void;
}

export interface SendMessageConfig {
  promptId: string;
  caseId?: string;
  templateId?: string;
  titleId?: string;
  idCard?: string[];
  withContext?: boolean;
  isThinking?: boolean;
  toPdf?: boolean;
}

// ==================== 主 Hook ====================
export function useChat(options: UseChatOptions = {}) {
  const {
    apiEndpoint = "/v1/chat/completions",
    withContext = false,
    onError,
    onSuccess,
  } = options;

  const userId = 1;

  // ==================== 状态管理 ====================
  const [historyItems, setHistoryItems] = useState<HistoryVO[]>([]);
  const [messages, setMessages] = useState<Message[]>([]);
  const [isTyping, setIsTyping] = useState(false);
  const [loading, setLoading] = useState(false);
  const [chatTitleId, setChatTitleId] = useState<string>("");
  const [currentPromptId, setCurrentPromptId] = useState<string>("");
  const [currentCaseId, setCurrentCaseId] = useState<string>("");
  const [isGeneratingTitle, setIsGeneratingTitle] = useState(false);
  const titleGeneratedRef = useRef(false); // 标记是否已生成过标题

  // ==================== Refs ====================
  const controllerRef = useRef<AbortController | null>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const tempMsgCounterRef = useRef(0);

  // ==================== 工具函数 ====================

  /** 获取当前时间 HH:MM */
  const getCurrentTime = () => {
    return new Date().toLocaleTimeString("zh-CN", {
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  /** 创建临时 AI 消息 */
  const createAiMessage = useCallback((): Message => {
    const tempId = `temp_${Date.now()}_${++tempMsgCounterRef.current}`;
    return {
      id: tempId,
      content: "",
      type: "ai",
      createTime: getCurrentTime(),
      loading: true,
      thinking: true,
    };
  }, []);

  /** 从流数据中提取文本内容 */
  const extractTextFromChunk = (jsonData: any): string => {
    return (
      jsonData?.choices?.[0]?.delta?.content ||
      jsonData?.result?.output?.text ||
      jsonData?.results?.[0]?.output?.text ||
      ""
    );
  };

  /** 从流数据中提取服务端消息ID */
  const extractIdFromChunk = (jsonData: any): string | null => {
    const paths = [
      jsonData?.metadata?.id,
      jsonData?.result?.output?.metadata?.id,
      jsonData?.results?.[0]?.output?.metadata?.id,
    ];

    for (const id of paths) {
      if (typeof id === "string" && id.length > 0) return id;
    }
    return null;
  };

  /** 提取HTML内容（用于PDF转换） */
  const extractHtmlContent = (content: string): string => {
    if (!content || typeof content !== "string") return content || "";

    // 匹配 ```html 代码块
    const htmlMatch = content.match(/```html\s*\n([\s\S]*?)\n```/);
    if (htmlMatch?.[1]) return htmlMatch[1].trim();

    // 匹配普通代码块
    const codeMatch = content.match(/```\s*\n([\s\S]*?)\n```/);
    if (codeMatch?.[1]) return codeMatch[1].trim();

    return content;
  };

  // ==================== 滚动相关 ====================

  /** 滚动到底部 */
  const scrollToBottom = useCallback(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, []);

  /** 如果已在底部则滚动到底部 */
  const scrollToBottomIfAtBottom = useCallback(() => {
    const container = messagesEndRef.current?.parentElement;
    if (!container) return;

    const isAtBottom =
      container.scrollHeight - container.scrollTop - container.clientHeight <
      100;

    if (isAtBottom) scrollToBottom();
  }, [scrollToBottom]);

  // 消息变化时自动滚动
  useEffect(() => {
    scrollToBottom();
  }, [messages, isTyping, scrollToBottom]);

  // ==================== 标题和历史记录 ====================

  /** 确保有对话标题 */
  const ensureChatTitle = useCallback(
    async (input: string, promptId: string): Promise<string | null> => {
      if (chatTitleId) return chatTitleId;

      const titleStr = input.replace(/\s+/g, "").slice(0, 20) + "...";

      try {
        const res = await addChatTitle({
          promptsId: promptId,
          title: titleStr,
        });

        if (res.code !== 200) {
          onError?.("添加标题失败");
          return null;
        }

        const newTitleId = res.data;
        setChatTitleId(newTitleId);
        return newTitleId;
      } catch (error) {
        console.error("添加标题失败:", error);
        onError?.("添加标题失败");
        return null;
      }
    },
    [chatTitleId, onError]
  );

  /** 获取历史记录 */
  const getHistorys = useCallback(
    async (
      promptId: string,
      pageNum: number = 1, // 新增
      pageSize: number = 10 // 新增
    ) => {
      // 修改API调用参数
      const res = await historyList({
        pageNum, // 使用传入的页码
        pageSize, // 使用传入的每页数量
        promptsId: promptId,
        userId,
      });

      // 修改返回值，返回完整的分页信息
      return {
        rows: res.rows,
        total: res.total, // 新增：总记录数
        hasMore: res.rows.length === pageSize, // 新增：是否有更多
      };

      // 不要在这里直接 setHistoryItems，让调用方处理
    },
    []
  );

  const generateTitleStream = useCallback(
    async (
      titleId: string,
      promptId: string,
      question: string,
      answer: string
    ) => {
      // 如果已经生成过标题，直接返回
      if (titleGeneratedRef.current) return;

      setIsGeneratingTitle(true);

      // 1. 添加占位数据到历史记录列表
      const placeholderItem: HistoryVO = {
        id: "slice-data",
        title: "标题生成中...",
        promptsId: promptId,
        createTime: new Date().toLocaleString(),
        userId: 1,
      };

      setHistoryItems((prev) => [placeholderItem, ...prev]);

      try {
        // 2. 创建中断控制器
        const controller = new AbortController();

        // 3. 调用AI流式接口生成标题
        const response = await fetch(
          `${import.meta.env.VITE_APP_BASE_API}/v1/chat/title`, // 根据实际接口调整
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              Authorization: "Bearer " + useAuthStore.getState().token,
              clientid: import.meta.env.VITE_APP_CLIENT_ID,
            },
            body: JSON.stringify({
              titleId,
              aiPromptsId: promptId,
              questions: [question, answer],
              // 其他必要参数（如果需要特殊标识生成标题）
            }),
            signal: controller.signal,
          }
        );

        // 4. 处理流式响应
        const reader = response.body?.getReader();
        if (!reader) throw new Error("无法读取流式响应");

        const decoder = new TextDecoder("utf-8");
        let buffer = "";
        let generatedTitle = "";

        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          buffer += decoder.decode(value, { stream: true });
          const lines = buffer.split("\n");
          buffer = lines.pop() || "";

          for (const rawLine of lines) {
            const line = rawLine.trim();
            if (!line || !line.startsWith("data:")) continue;

            const jsonStr = line.replace(/^data:\s*/, "");
            if (jsonStr === "[DONE]") continue;

            try {
              const jsonData = JSON.parse(jsonStr);
              const delta = extractTextFromChunk(jsonData);

              if (delta) {
                generatedTitle += delta;

                // 5. 实时更新占位数据的标题
                setHistoryItems((prev) =>
                  prev.map((item) =>
                    item.id === "slice-data"
                      ? { ...item, title: generatedTitle }
                      : item
                  )
                );
              }
            } catch (err) {
              console.error("解析标题生成 JSON 失败:", err);
            }
          }
        }

        // 6. 流式结束后，获取最新的历史记录
        const latestHistory = await getHistorys(promptId, 1, 1);

        if (latestHistory && latestHistory.rows.length > 0) {
          const realHistoryItem = latestHistory.rows[0];

          // 7. 替换占位数据
          setHistoryItems((prev) =>
            prev.map((item) =>
              item.id === "slice-data" ? realHistoryItem : item
            )
          );
        }

        // 8. 标记已生成标题
        titleGeneratedRef.current = true;
      } catch (error: any) {
        console.error("生成标题失败:", error);

        // 失败时移除占位数据
        setHistoryItems((prev) =>
          prev.filter((item) => item.id !== "slice-data")
        );
      } finally {
        setIsGeneratingTitle(false);
      }
    },
    [extractTextFromChunk, getHistorys]
  );

  // ==================== 核心发送消息逻辑 ====================

  const sendMessage = useCallback(
    async (input: string, config: SendMessageConfig) => {
      if (!input.trim()) return;

      // ✅ 在发送消息前就记录状态
      const isFirstConversation = messages.length === 0;

      // 1. 创建用户消息和临时AI消息
      const userMessage: Message = {
        id: Date.now().toString(),
        content: input,
        type: "user",
        createTime: new Date().toLocaleString(),
      };

      const aiMessageLocal = createAiMessage();
      let finalContent = "";

      setMessages((prev) => [...prev, userMessage, aiMessageLocal]);
      setLoading(true);
      setIsTyping(true);

      // 2. 创建中断控制器
      controllerRef.current = new AbortController();

      // 3. 确保有标题ID
      const titleId = await ensureChatTitle(input, config.promptId);
      if (!titleId) {
        setMessages((prev) =>
          prev.map((msg) =>
            msg.id === aiMessageLocal.id
              ? {
                  ...msg,
                  content: "添加标题失败",
                  loading: false,
                  thinking: false,
                }
              : msg
          )
        );
        setLoading(false);
        setIsTyping(false);
        return;
      }

      // 4. 构建请求参数
      const endpoint =
        config.withContext || withContext
          ? "/v1/context/chat/completions"
          : apiEndpoint;

      const requestBody: any = {
        questions: [input],
        titleId: titleId,
        type: "web",
      };

      if (config.promptId) requestBody.aiPromptsId = config.promptId;
      if (config.caseId) requestBody.caseNumbering = config.caseId;
      if (config.templateId) requestBody.templateId = config.templateId;
      if (config.idCard?.length) requestBody.idCard = config.idCard;
      if (config.isThinking) requestBody.think = "true";

      try {
        // 5. 发起请求
        const response = await fetch(
          `${import.meta.env.VITE_APP_BASE_API}${endpoint}`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              Authorization: "Bearer " + useAuthStore.getState().token,
              clientid: import.meta.env.VITE_APP_CLIENT_ID,
            },
            body: JSON.stringify(requestBody),
            signal: controllerRef.current?.signal,
          }
        );

        const contentType = response.headers.get("Content-Type") || "";

        // 6. 处理非流式响应
        if (!contentType.includes("text/event-stream")) {
          const errorResult = await response.json();

          const serverText =
            errorResult?.result?.output?.text ||
            errorResult?.results?.[0]?.output?.text ||
            errorResult?.data?.result?.output?.text ||
            errorResult?.msg ||
            "服务返回错误";

          const serverId =
            errorResult?.metadata?.id ||
            errorResult?.result?.output?.metadata?.id ||
            errorResult?.results?.[0]?.output?.metadata?.id;

          setMessages((prev) =>
            prev.map((msg) =>
              msg.id === aiMessageLocal.id
                ? {
                    ...msg,
                    id: serverId || msg.id,
                    content: serverText,
                    loading: false,
                    thinking: false,
                  }
                : msg
            )
          );

          onSuccess?.({
            ...aiMessageLocal,
            id: serverId || aiMessageLocal.id,
            content: serverText,
            loading: false,
            thinking: false,
          });

          setLoading(false);
          setIsTyping(false);
          return;
        }

        // 7. 处理流式响应
        const reader = response.body?.getReader();
        if (!reader) throw new Error("无法读取流式响应");

        const decoder = new TextDecoder("utf-8");
        let buffer = "";
        let serverMessageId: string | null = null;

        setIsTyping(false);

        while (true) {
          const { done, value } = await reader.read();

          if (done) {
            // 更新消息状态
            setMessages((prev) =>
              prev.map((msg) =>
                msg.id === (serverMessageId || aiMessageLocal.id)
                  ? {
                      ...msg,
                      content: finalContent || msg.content,
                      loading: false,
                      thinking: false,
                    }
                  : msg
              )
            );

            // PDF转换处理
            if (config.toPdf) {
              const htmlContent = extractHtmlContent(finalContent);
              console.log("需要显示PDF:", htmlContent);
            }
            if (isFirstConversation && !titleGeneratedRef.current) {
              console.log("🚀 开始生成标题");
              generateTitleStream(
                titleId,
                config.promptId,
                input,
                finalContent
              );
            }

            // 成功回调
            onSuccess?.({
              ...aiMessageLocal,
              id: serverMessageId || aiMessageLocal.id,
              content: finalContent,
              loading: false,
              thinking: false,
            });

            break;
          }

          // 处理流数据
          buffer += decoder.decode(value, { stream: true });
          const lines = buffer.split("\n");
          buffer = lines.pop() || "";

          for (const rawLine of lines) {
            const line = rawLine.trim();
            if (!line || !line.startsWith("data:")) continue;

            const jsonStr = line.replace(/^data:\s*/, "");
            if (jsonStr === "[DONE]") continue;

            let jsonData: any = null;
            try {
              jsonData = JSON.parse(jsonStr);
            } catch (err) {
              console.error("解析流行 JSON 失败:", err);
              continue;
            }

            // 提取服务端消息ID（仅首次）
            if (!serverMessageId) {
              const maybeId = extractIdFromChunk(jsonData);
              if (maybeId) {
                serverMessageId = maybeId;
                setMessages((prev) =>
                  prev.map((msg) =>
                    msg.id === aiMessageLocal.id
                      ? { ...msg, id: serverMessageId as string }
                      : msg
                  )
                );
              }
            }

            // 提取文本增量
            const delta = extractTextFromChunk(jsonData);
            if (delta) {
              finalContent += delta;

              setMessages((prev) =>
                prev.map((msg) => {
                  const matchId = serverMessageId || aiMessageLocal.id;
                  if (msg.id === matchId) {
                    return {
                      ...msg,
                      content: (msg.content || "") + delta,
                      thinking: false,
                      loading: true,
                    };
                  }
                  return msg;
                })
              );

              scrollToBottomIfAtBottom();
            }
          }
        }
      } catch (error: any) {
        console.error("请求失败:", error);

        const errorMessage =
          error?.name === "AbortError"
            ? finalContent || "已停止生成"
            : "抱歉，服务出现异常，请稍后重试";

        setMessages((prev) =>
          prev.map((msg) =>
            msg.id === aiMessageLocal.id
              ? {
                  ...msg,
                  content: errorMessage,
                  loading: false,
                  thinking: false,
                }
              : msg
          )
        );

        if (error?.name !== "AbortError") {
          onError?.(error?.message || "请求失败");
        }
      } finally {
        setLoading(false);
        setIsTyping(false);
      }
    },
    [
      apiEndpoint,
      withContext,
      createAiMessage,
      onError,
      onSuccess,
      scrollToBottomIfAtBottom,
      ensureChatTitle,
      generateTitleStream,
    ]
  );

  // ==================== 其他操作方法 ====================

  /** 停止生成 */
  const stopGeneration = useCallback(() => {
    controllerRef.current?.abort();
    setLoading(false);
    setIsTyping(false);
  }, []);

  /** 清空消息 */
  const clearMessages = useCallback(() => {
    setMessages([]);
    setChatTitleId("");
    titleGeneratedRef.current = false; // 新增：重置标题生成标记
  }, []);

  /** 删除消息 */
  const deleteMessage = useCallback((id: string) => {
    setMessages((prev) => prev.filter((msg) => msg.id !== id));
  }, []);

  /** 复制消息（移除HTML标签） */
  const copyMessage = useCallback((text: string) => {
    const plainText = (text || "").replace(/<[^>]*>/g, "");
    navigator.clipboard.writeText(plainText).then(
      () => console.log("复制成功"),
      (err) => console.error("复制失败:", err)
    );
  }, []);

  /** 加载历史对话 */
  const loadHistory = useCallback(
    async (titleId: string) => {
      try {
        setChatTitleId(titleId);
        titleGeneratedRef.current = true; // 新增：标记为已生成（因为是加载的历史）
        // TODO: 调用获取历史记录API
        const res = await getTitleDetail({
          pageNum: 1,
          pageSize: 100,
          titleId,
        });
        if (res.code === 200) setMessages(res.rows);
        console.log("加载历史记录:", titleId);
      } catch (error) {
        console.error("加载历史记录失败:", error);
        onError?.("加载历史记录失败");
      }
    },
    [onError]
  );

  // ==================== 返回值 ====================
  return {
    // 状态
    messages,
    historyItems,
    isTyping,
    loading,
    chatTitleId,
    currentCaseId,
    currentPromptId,
    isGeneratingTitle,

    // Refs
    messagesEndRef,

    // 方法
    sendMessage,
    stopGeneration,
    clearMessages,
    deleteMessage,
    copyMessage,
    loadHistory,
    getHistorys,

    // Setters
    setMessages,
    setChatTitleId,
    setCurrentCaseId,
    setCurrentPromptId,
    setHistoryItems,
  };
}
